package com.fyy.netty.chapter03.c1;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.AdaptiveRecvByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.FixedLengthFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @Author fyy
 * @Description 定长解码器服务器端
 * @Date 2021/5/10 14:30
 */
@Slf4j
public class FixLengthDecoderServer {

    public void start(){
        //声明工作线程及主线程
        NioEventLoopGroup boss = new NioEventLoopGroup(1);
        NioEventLoopGroup worker = new NioEventLoopGroup();
        try {
            //启动配置
            ServerBootstrap server = new ServerBootstrap();
            server.channel(NioServerSocketChannel.class); //非阻塞
            //调整系统的接收缓冲区(滑动窗口)
            //server.option(ChannelOption.SO_RCVBUF,10); //设置接收缓冲区
            //调整netty的接收缓冲区(ByteBuf)
            server.childOption(ChannelOption.RCVBUF_ALLOCATOR,new AdaptiveRecvByteBufAllocator(16,16,32));
            server.group(boss,worker);
            server.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel sc) throws Exception {
                    sc.pipeline().addLast(new FixedLengthFrameDecoder(10)); //添加定长解吗器
                    sc.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                }
            });
            ChannelFuture future = server.bind(8080).sync();
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            log.error("服务器启动错误：{}",e.getMessage());
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        new StickingHalfServer().start();
    }

}
